package com.home.auto_navigation.common;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.support.PageFactory;

import com.home.auto_navigation.ui.pages.HomePage;

public class Driver {

	private RemoteWebDriver driver;

	private static Driver instance;

	private Driver() {
		driver = Browser.valueOf(Config.getProperty("browser")).openBrowser(driver);
	}

	public static Driver getInstance() {
		if (instance != null) {
			return instance;
		} else {
			return instance= new Driver();
		}
	}

	public boolean isElementPresent(By locator) {
		return driver.findElements(locator).size() > 0;
	}

	public HomePage openHomePage() {
		// driver.get("https://www.google.com.ua/");
		// driver.get("http://www.oracle.com");
		System.out.println(Config.getProperty("url"));
		driver.get(Config.getProperty("url"));
		return PageFactory.initElements(driver, HomePage.class);
	}

	public void maximizeWindow() {
		driver.manage().window().maximize();
	}

	public void implicitlyWait(int time, TimeUnit timeUnit) {
		driver.manage().timeouts().implicitlyWait(1, TimeUnit.MILLISECONDS);
	}

	/**
	 * set value from properties file
	 * */
	public void implicitlyWait() {
		driver.manage().timeouts()
				.implicitlyWait(Config.getIntProperty("timeout"),
						TimeUnit.SECONDS);
	}
	
	public void executeScript(String script, WebElement webElement){
		driver.executeScript(script, webElement);
	}
	
	public void openUrl(String url){
		driver.get(url);
	}
	
	public void close(){
		driver.close();
	}
	
	public RemoteWebDriver getDriver(){
		return driver;
	}
	
	public void takesScreenshot(){
		File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
	    try {
			FileUtils.copyFile(scrFile, new File("screenshot.png"));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
